layui.use(['layedit','form','laydate'], function(){
    var layedit = layui.layedit;
    var laydate = layui.laydate;
    var form = layui.form;

    //设置图片上传接口
    layedit.set({
        uploadImage: {
            //接口url
            url: '../../fileUpload/image'
        }
    });

    var index = layedit.build('news-textarea',{
        height: 666,
    }); //建立编辑器

    //渲染日期
    laydate.render({
        elem: '#createTime' //指定元素
        ,type: 'datetime'
    });
    laydate.render({
        elem: '#newsAnnounceTime' //指定元素
        ,type: 'datetime'
    });

    var getQueryString = function (name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURIComponent(r[2]);
        };
        return null;
    };

    var loadNews = function (){
        var newsid = getQueryString("news");
        if (newsid == null || newsid==''){
            //结束程序
            return;
        }

        CoreUtil.sendAjax("/news/byId/"+newsid,'' , function (res) {
            if (res.data != null) {
                form.val("news-text",res.data);
                layedit.setContent(index,res.data.newsContent);
            } else {
                layer.msg('查询失败', {icon: 2});
            }
        }, "POST", false, function (res) {
            layer.msg('站点出问题啦！请联系管理员', {icon: 6})
        });
    };

    //监听提交
    form.on('submit(submitChange)', function(data){

        data.field.newsContent = layedit.getContent(index);

        $.ajax({
            url:'/news/saveOrUpdateNews',
            type:'POST', //GET
            async:true,    //或false,是否异步
            data: JSON.stringify(data.field),
            timeout:5000,
            dataType:'json',
            contentType: "application/json",
            success:function(data){
                if (data.code == '0'){
                    layer.msg("提交成功！",{icon:6});
                    loadNews();
                }
            }
        });
        return false;
    });

    loadNews()
});